/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package slsBeans;

import EL.*;

import java.util.*;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author Tian
 */
@Stateless
public class AccountBLO implements AccountBLORemote
{

    @PersistenceContext(unitName = "Tunga_EJB3PU")
    private EntityManager em;

    public List<Accounts> getAll()
    {
        String hql = "FROM Accounts";
        Query query = this.em.createQuery(hql);
        List<Accounts> accounts = query.getResultList();
        return accounts;
    }

    public Accounts getByID(int id)
    {
        Accounts acc = this.em.find(Accounts.class, id);
        return acc;
    }

    public Accounts getByName(String name)
    {
        String hql = "FROM Accounts where username=?1";
        Query query = this.em.createQuery(hql);
        query.setParameter(1, name);
        Accounts acc = (Accounts) query.getSingleResult();
        return acc;
    }

    public Accounts add(Contacts contact, Accounts account)
    {
        try
        {
            contact.setAccounts(account);
            account.setContacts(contact);
            this.em.persist(contact);
            return account;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return null;
        }

    }

    public boolean edit(Accounts acc)
    {
        try
        {
            this.em.merge(acc);
            return true;
        }
        catch (Exception e)
        {
            return false;
        }
        
    }

    public boolean delete(int id)
    {
        Contacts contact = getContByID(id);
        if (contact != null)
        {
            try
            {
                this.em.remove(contact);
                return true;
            }
            catch (Exception e)
            {
                e.printStackTrace();
                return false;
            }
        }
        return false;
    }

    public Accounts checkLogin(String username, String password)
    {
        try
        {
            String hql = "FROM Accounts WHERE username=?1 and password=?2";
            Query query = this.em.createQuery(hql);
            query.setParameter(1, username);
            query.setParameter(2, password);
            Accounts acc = (Accounts) query.getSingleResult();
            return acc;
        }
        catch (Exception e)
        {
            return null;
        }
    }

    public Contacts getContByID(int id)
    {
        Contacts contact = em.find(Contacts.class, id);
        return contact;
    }
}
